// 添加客户按钮点击事件
document.getElementById('addCustomerBtn').addEventListener('click', function() {
    document.getElementById('modalTitle').textContent = '添加新客户';
    document.getElementById('customerForm').reset();
    document.getElementById('customerId').value = '';

    const modal = new bootstrap.Modal(document.getElementById('customerModal'));
    modal.show();
});

// 搜索按钮事件
document.getElementById('searchBtn').addEventListener('click', function() {
    const customerId = document.getElementById('customerIdSearch').value;
    const idCard = document.getElementById('idCardSearch').value;

    // 构建查询URL
    const params = new URLSearchParams();
    if (customerId) params.append('customerId', customerId);
    if (idCard) params.append('idCard', idCard);

    // 重定向到搜索页面
    window.location.href = `/admin/admin_clientmanage?${params.toString()}`;
});

// 导出CSV按钮点击事件
document.getElementById('exportCsvBtn').addEventListener('click', function() {
    const customerId = document.getElementById('customerIdSearch').value;
    const idCard = document.getElementById('idCardSearch').value;

    // 构建查询参数
    const params = new URLSearchParams();
    if (customerId) params.append('customerId', customerId);
    if (idCard) params.append('idCard', idCard);

    // 触发下载
    window.location.href = `/admin/export_customers_csv?${params.toString()}`;
});

// 查看客户详情
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('view-btn') || e.target.closest('.view-btn')) {
        const btn = e.target.classList.contains('view-btn') ? e.target : e.target.closest('.view-btn');
        const customerId = btn.getAttribute('data-id');

        // 获取客户详情
        fetch(`/admin/get_customer/${customerId}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert(data.error);
                    return;
                }

                // 填充基本信息
                document.getElementById('detailCustomerName').textContent = data.customer.name;
                document.getElementById('detailCustomerId').textContent = data.customer.id;
                document.getElementById('detailIdCard').textContent = data.customer.idCard;
                document.getElementById('detailPhone').textContent = data.customer.phone;
                document.getElementById('detailAddress').textContent = data.customer.address;

                // 填充账户概览
                const accountOverview = document.getElementById('accountOverview');
                if (data.cards && data.cards.length > 0) {
                    const totalBalance = data.cards.reduce((sum, card) => sum + card.balance, 0);
                    accountOverview.innerHTML = `
                        <p><strong>银行卡数量：</strong> ${data.cards.length}</p>
                        <p><strong>总余额：</strong> ${totalBalance.toFixed(2)}</p>
                        <p><strong>最近交易：</strong> ${data.recentTransactions.length > 0 ? data.recentTransactions[0].date : '无'}</p>
                    `;
                } else {
                    accountOverview.innerHTML = '<p class="text-muted">该客户暂无银行卡</p>';
                }

                // 填充银行卡信息
                const cardsTable = document.getElementById('bankCardsTable').querySelector('tbody');
                cardsTable.innerHTML = '';
                if (data.cards.length > 0) {
                    data.cards.forEach(card => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${card.cardID}</td>
                            <td>${card.currency}</td>
                            <td>${card.balance.toFixed(2)}</td>
                            <td>${card.status}</td>
                            <td>${card.openDate || '未知'}</td>
                        `;
                        cardsTable.appendChild(row);
                    });
                } else {
                    cardsTable.innerHTML = '<tr><td colspan="5" class="text-center">暂无银行卡</td></tr>';
                }

                // 填充交易记录
                const transactionsTable = document.getElementById('recentTransactionsTable').querySelector('tbody');
                transactionsTable.innerHTML = '';
                if (data.recentTransactions.length > 0) {
                    data.recentTransactions.forEach(transaction => {
                        const row = document.createElement('tr');
                        const amountClass = transaction.type === '存款' ? 'text-success' : 'text-danger';
                        row.innerHTML = `
                            <td>${transaction.date}</td>
                            <td>${transaction.type}</td>
                            <td class="${amountClass}">${transaction.amount.toFixed(2)}</td>
                            <td>${transaction.remark || '-'}</td>
                        `;
                        transactionsTable.appendChild(row);
                    });
                } else {
                    transactionsTable.innerHTML = '<tr><td colspan="4" class="text-center">暂无交易记录</td></tr>';
                }

                // 显示模态框
                const modal = new bootstrap.Modal(document.getElementById('customerDetailModal'));
                modal.show();
            })
            .catch(error => {
                console.error('获取客户详情失败:', error);
                alert('获取客户详情时出错');
            });
    }
});

// 编辑按钮事件
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('edit-btn') || e.target.closest('.edit-btn')) {
        const btn = e.target.classList.contains('edit-btn') ? e.target : e.target.closest('.edit-btn');
        const customerId = btn.getAttribute('data-id');
        const row = btn.closest('tr');

        // 填充表单数据
        document.getElementById('modalTitle').textContent = '编辑客户信息';
        document.getElementById('customerId').value = customerId;
        document.getElementById('customerName').value = row.cells[1].textContent;
        document.getElementById('idCard').value = row.cells[2].textContent;
        document.getElementById('telephone').value = row.cells[3].textContent;
        document.getElementById('address').value = row.cells[4].textContent;

        const modal = new bootstrap.Modal(document.getElementById('customerModal'));
        modal.show();
    }
});

// 删除按钮事件
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('delete-btn') || e.target.closest('.delete-btn')) {
        const btn = e.target.classList.contains('delete-btn') ? e.target : e.target.closest('.delete-btn');
        const customerId = btn.getAttribute('data-id');
        const customerName = btn.closest('tr').cells[1].textContent;

        if (confirm(`确定要删除客户 ${customerName} 吗？`)) {
            fetch(`/admin/delete_customer/${customerId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert(data.message);
                }
            })
            .catch(error => {
                console.error('删除失败:', error);
                alert('删除客户时出错');
            });
        }
    }
});

// 保存客户信息
document.getElementById('saveCustomerBtn').addEventListener('click', function() {
    const formData = {
        name: document.getElementById('customerName').value,
        idCard: document.getElementById('idCard').value,
        phone: document.getElementById('telephone').value,
        address: document.getElementById('address').value
    };

    // 表单验证
    if (!formData.name || !formData.idCard || !formData.phone || !formData.address) {
        alert('请填写所有必填字段');
        return;
    }

    const customerId = document.getElementById('customerId').value;
    const url = customerId ? `/admin/update_customer/${customerId}` : '/admin/add_customer';
    const method = customerId ? 'PUT' : 'POST';

    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            location.reload();
        } else {
            alert(data.message);
        }
    })
    .catch(error => {
        console.error('保存失败:', error);
        alert('保存客户信息时出错');
    });
});